<?php
/*
  Plugin Name: MCMS4WP
  Plugin URI: http://alexrabe.de/?page_id=80
  Description: My simple CMS for wordpress
  Author: Jiang Hongfei
  Version: 1.0.0

  Author URI: http://zhentmd.com

  Copyright 2007-2011 by Alex Rabe & NextGEN DEV-Team

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

 */

if (!class_exists('mcmsLoader')) {

    class mcmsLoader {

        var $version = '1.0.0';

        function mcmsLoader() {

            // Stop the plugin if we missed the requirements
            if (!$this->check_memory_limit())
                return;

            // Get some constants first
            $this->load_options();
            $this->define_constant();
            $this->define_tables();
            $this->load_dependencies();

            $this->plugin_name = plugin_basename(__FILE__);

            // Init options & tables during activation & deregister init option
            register_activation_hook($this->plugin_name, array(&$this, 'activate'));
            register_deactivation_hook($this->plugin_name, array(&$this, 'deactivate'));

            // Register a uninstall hook to remove all tables & option automatic
            register_uninstall_hook($this->plugin_name, array('nggLoader', 'uninstall'));

            // Start this plugin once all other plugins are fully loaded
            add_action('plugins_loaded', array(&$this, 'start_plugin'));

            //Add some links on the plugin page
            add_filter('plugin_row_meta', array(&$this, 'add_plugin_links'), 10, 2);
        }

        function start_plugin() {
            // Check if we are in the admin area
            if (is_admin()) {

                // Pass the init check or show a message
                if (get_option('mcms_init_check') != false)
                    add_action('admin_notices', create_function('', 'echo \'<div id="message" class="error"><p><strong>' . get_option("mcms_init_check") . '</strong></p></div>\';'));
            }

            // Look for XML request, before page is render
            add_action('parse_request', array(&$this, 'check_request'));

            // Add a version number to the header
            add_action('wp_head', create_function('', 'echo "\n<meta name=\'NextGEN\' content=\'' . $this->version . '\' />\n";'));
            add_action('wp_dashboard_setup', array(&$this, 'add_dashboard_widget'));

            add_action('comment_post', array('mcmsLoader', 'comment_post'));

            // Add the script and style files
            add_action('template_redirect', array(&$this, 'load_scripts'));

            //add_action('admin_head', array('mcmsLoader', 'all_styles'));
        }

        function all_styles() {
            global $wp_styles;
            echo 'hongfei';
            print_r($wp_styles->registered);
        }
        
        function comment_post($comment_ID, $comment_approved) {
            $fp = fopen(MCMS_ABSPATH . 'log.txt', 'a');
            fwrite($fp, "ID: $comment_ID;approved: $comment_approved");
            fclose($fp);
        }

        function log($message) {
            $fp = fopen(MCMS_ABSPATH . 'log.txt', 'a');
            fwrite($fp, $message);
            fclose($fp);
        }

        function check_request($wp) {

            if (!array_key_exists('callback', $wp->query_vars))
                return;

            if ($wp->query_vars['callback'] == 'imagerotator') {
                require_once (dirname(__FILE__) . '/xml/imagerotator.php');
                exit();
            }

            if ($wp->query_vars['callback'] == 'json') {
                require_once (dirname(__FILE__) . '/xml/json.php');
                exit();
            }

            if ($wp->query_vars['callback'] == 'image') {
                require_once (dirname(__FILE__) . '/nggshow.php');
                exit();
            }

            //TODO:see trac #12400 could be an option for WP3.0 
            if ($wp->query_vars['callback'] == 'ngg-ajax') {
                require_once (dirname(__FILE__) . '/xml/ajax.php');
                exit();
            }
        }

        function check_memory_limit() {

            // get the real memory limit before some increase it
            $this->memory_limit = ini_get('memory_limit');

            // Yes, we reached Gigabyte limits, so check if it's a megabyte limit
            if (strtolower(substr($this->memory_limit, -1)) == 'm') {

                $this->memory_limit = (int) substr($this->memory_limit, 0, -1);

                //This works only with enough memory, 16MB is silly, wordpress requires already 16MB :-)
                if (($this->memory_limit != 0) && ($this->memory_limit < 16 )) {
                    add_action(
                            'admin_notices', create_function(
                                    '', 'echo \'<div id="message" class="error"><p><strong>' . __('Sorry, MCMS works only with a Memory Limit of 16 MB or higher', 'nggallery') . '</strong></p></div>\';'
                            )
                    );
                    return false;
                }
            }

            return true;
        }

        function define_tables() {
            global $wpdb;

            // add database pointer 
            $wpdb->mcms_service = $wpdb->prefix . 'mcms_service';
        }

        function register_taxonomy() {
            global $wp_rewrite;

            // Register the NextGEN taxonomy
            $args = array(
                'label' => __('Picture tag', 'nggallery'),
                'template' => __('Picture tag: %2$l.', 'nggallery'),
                'helps' => __('Separate picture tags with commas.', 'nggallery'),
                'sort' => true,
                'args' => array('orderby' => 'term_order')
            );

            register_taxonomy('ngg_tag', 'nggallery', $args);
        }

        function define_constant() {

            //TODO:SHOULD BE REMOVED LATER
            define('MCMS_VERSION', $this->version);

            // required for Windows & XAMPP
            define('WINABSPATH', str_replace("\\", "/", ABSPATH));

            // define URL
            define('MCMS_FOLDER', plugin_basename(dirname(__FILE__)));

            define('MCMS_ABSPATH', trailingslashit(str_replace("\\", "/", WP_PLUGIN_DIR . '/' . plugin_basename(dirname(__FILE__)))));
            define('MCMS_URLPATH', trailingslashit(plugins_url('', __FILE__)));
        }

        function load_dependencies() {

//		// Load global libraries												// average memory usage (in bytes)
//		require_once (dirname (__FILE__) . '/lib/core.php');					//  94.840
//		require_once (dirname (__FILE__) . '/lib/ngg-db.php');					// 132.400
//		require_once (dirname (__FILE__) . '/lib/image.php');					//  59.424
//		require_once (dirname (__FILE__) . '/lib/tags.php');				    // 117.136
//		require_once (dirname (__FILE__) . '/lib/post-thumbnail.php');			//  n.a.
//		require_once (dirname (__FILE__) . '/widgets/widgets.php');				// 298.792
//        require_once (dirname (__FILE__) . '/lib/multisite.php');
//        require_once (dirname (__FILE__) . '/lib/sitemap.php');
//
//        // Load frontend libraries							
//        require_once (dirname (__FILE__) . '/lib/navigation.php');		        // 242.016
//        require_once (dirname (__FILE__) . '/nggfunctions.php');		        // n.a.
//		require_once (dirname (__FILE__) . '/lib/shortcodes.php'); 		        // 92.664
//
//		//Just needed if you access remote to WordPress
//		if ( defined('XMLRPC_REQUEST') )
//			require_once (dirname (__FILE__) . '/lib/xmlrpc.php');
//			
//		// We didn't need all stuff during a AJAX operation
//		if ( defined('DOING_AJAX') )
//			require_once (dirname (__FILE__) . '/admin/ajax.php');
//		else {
//			require_once (dirname (__FILE__) . '/lib/meta.php');				// 131.856
//			require_once (dirname (__FILE__) . '/lib/media-rss.php');			//  82.768
//			require_once (dirname (__FILE__) . '/lib/rewrite.php');				//  71.936
//			include_once (dirname (__FILE__) . '/admin/tinymce/tinymce.php'); 	//  22.408
//
//			// Load backend libraries
//			if ( is_admin() ) {	
//				require_once (dirname (__FILE__) . '/admin/admin.php');
//				require_once (dirname (__FILE__) . '/admin/media-upload.php');
//				$this->nggAdminPanel = new nggAdminPanel();
//			}	
//		}
        }

        function load_options() {
            // Load the options
            $this->options = get_option('mcms_options');
        }

        function load_scripts() {
//
//            // if you don't want that NGG load the scripts, add this constant
//            if (defined('NGG_SKIP_LOAD_SCRIPTS'))
//                return;
//
//            //	activate Thickbox
//            if ($this->options['thumbEffect'] == 'thickbox') {
//                wp_enqueue_script('thickbox');
//                // Load the thickbox images after all other scripts
//                add_action('wp_footer', array(&$this, 'load_thickbox_images'), 11);
//            }
//
//            // activate modified Shutter reloaded if not use the Shutter plugin
//            if (($this->options['thumbEffect'] == "shutter") && !function_exists('srel_makeshutter')) {
//                wp_register_script('shutter', NGGALLERY_URLPATH . 'shutter/shutter-reloaded.js', false, '1.3.2');
//                wp_localize_script('shutter', 'shutterSettings', array(
//                    'msgLoading' => __('L O A D I N G', 'nggallery'),
//                    'msgClose' => __('Click to Close', 'nggallery'),
//                    'imageCount' => '1'
//                ));
//                wp_enqueue_script('shutter');
//            }
//
//            // required for the slideshow
//            if (NGGALLERY_IREXIST == true && $this->options['enableIR'] == '1' && nggGallery::detect_mobile_phone() === false)
//                wp_enqueue_script('swfobject', NGGALLERY_URLPATH . 'admin/js/swfobject.js', FALSE, '2.2');
//            else {
//                wp_register_script('jquery-cycle', NGGALLERY_URLPATH . 'js/jquery.cycle.all.min.js', array('jquery'), '2.88');
//                wp_enqueue_script('ngg-slideshow', NGGALLERY_URLPATH . 'js/ngg.slideshow.min.js', array('jquery-cycle'), '1.05');
//            }
//
//            // Load AJAX navigation script, works only with shutter script as we need to add the listener
//            if ($this->options['galAjaxNav']) {
//                if (($this->options['thumbEffect'] == "shutter") || function_exists('srel_makeshutter')) {
//                    wp_enqueue_script('ngg_script', NGGALLERY_URLPATH . 'js/ngg.js', array('jquery'), '2.0');
//                    wp_localize_script('ngg_script', 'ngg_ajax', array('path' => NGGALLERY_URLPATH,
//                        'callback' => home_url() . '/' . 'index.php?callback=ngg-ajax',
//                        'loading' => __('loading', 'nggallery'),
//                    ));
//                }
//            }
        }

        function load_styles() {
            wp_enqueue_style('dashboard_mcms_services', MCMS_URLPATH . 'css/dashboard.css');
            $fp = fopen(MCMS_ABSPATH . 'log.txt', 'a');
            fwrite($fp, MCMS_URLPATH . 'css/dashboard.css');
            fclose($fp);
        }

        function activate() {
            global $wpdb;

            include_once (dirname(__FILE__) . '/include/install.php');

            // check for tables
            mcms_install();
        }

        function deactivate() {

            // remove & reset the init check option
            delete_option('mcms_init_check');
        }

        function uninstall() {
            include_once (dirname(__FILE__) . '/include/install.php');
            mcms_uninstall();
        }

        // Taken from Google XML Sitemaps from Arne Brachhold
        function add_plugin_links($links, $file) {

            if ($file == plugin_basename(__FILE__)) {
                $links[] = '<a href="admin.php?page=nextgen-gallery">' . __('Overview', 'nggallery') . '</a>';
                $links[] = '<a href="http://wordpress.org/tags/nextgen-gallery?forum_id=10">' . __('Get help', 'nggallery') . '</a>';
                $links[] = '<a href="http://code.google.com/p/nextgen-gallery/">' . __('Contribute', 'nggallery') . '</a>';
                $links[] = '<a href="http://alexrabe.de/donation/">' . __('Donate', 'nggallery') . '</a>';
            }
            return $links;
        }

        function mcms_service_management_dashboard_widget() {
            global $wpdb;
            $services = $wpdb->get_results("SELECT * FROM $wpdb->mcms_service");
            //mcmsLoader::load_styles();
            ?>
            <form style="margin-bottom: 10px;" name="post" action="http://localhost:85/wordpress/wp-admin/post.php" method="post" id="quick-press">
                <h4 id="quick-post-title"><label for="title">Name</label></h4>
                <div class="input-text-wrap">
                    <input type="text" name="post_title" id="title" tabindex="1" autocomplete="off" value="">
                </div>

                <h4 id="content-label"><label for="content">Content</label></h4>
                <div class="textarea-wrap">
                    <textarea name="content" id="content" class="mceEditor" rows="3" cols="15" tabindex="2"></textarea>
                </div>

                <script type="text/javascript">edCanvas = document.getElementById('content');edInsertContent = null;</script>

                <h4><label for="tags-input">Price</label></h4>
                <div class="input-text-wrap">
                    <input type="text" name="tags_input" id="tags-input" tabindex="3" value="">
                </div>

                <p class="submit">
                    <input type="hidden" name="action" id="quickpost-action" value="post-quickpress-save">
                    <input type="hidden" name="quickpress_post_ID" value="3">
                    <input type="hidden" name="post_type" value="post">
                    <input type="hidden" id="_wpnonce" name="_wpnonce" value="a0a37f73fc">
                    <input type="hidden" name="_wp_http_referer" value="/wordpress/wp-admin/index.php">
                    <input type="submit" name="save" id="save-post" class="button" value="Save Service" tabindex="4">
                    <input type="reset" value="Reset" class="button">
                    <span id="publishing-action">
                        <input type="submit" name="publish" id="publish" accesskey="p" tabindex="5" class="button-primary" value="Publish">
                        <img class="waiting" src="http://localhost:85/wordpress/wp-admin/images/wpspin_light.gif" alt="">
                    </span>
                    <br class="clear">
                </p>

            </form>
            <?php
            foreach ($services as $service) {
                echo "<h5 style=\"font-weight: 800; font-size: 13px; display: inline;\">$service->name</h5>
                <span>($service->price)</span>
                <p style=\"font-size: 10px; margin: 0.3em 0; line-height: 1.4em;\"><span><a href=\"#\">编辑</a></span> | <span><a href=\"#\">删除</a></span></p>
                <p style=\"margin: 0.3em 0 1.4em; line-height: 1.4em;\">$service->description</p>";
            }

            echo '<p><a href="http://wordpress.org/">WordPress</a> is a state-of-the-art publishing platform with a focus on aesthetics, web standards, and usability. WordPress is both free and priceless at the same time.</p>';
        }

        // Check out Actions Run During an Admin Page Request at http://codex.wordpress.org/Plugin_API/Action_Reference
        function add_dashboard_widget() {
            add_action('admin_enqueue_scripts', array('mcmsLoader', 'load_styles'));
            wp_add_dashboard_widget('dashboard_mcms_services', 'Services Management', array(&$this, 'mcms_service_management_dashboard_widget'));
        }

    }

    global $loader;
    $loader = new mcmsLoader();
}
